package com.suishoupai.xmb.controller;

import com.github.pagehelper.Page;
import com.suishoupai.xmb.entity.AjaxMessage;
import com.suishoupai.xmb.entity.Category;
import com.suishoupai.xmb.service.CategoryService;
import com.suishoupai.xmb.service.GoodsService;
import com.suishoupai.xmb.utils.PageUtil;
import com.suishoupai.xmb.utils.SecurityUserUtil;
import com.suishoupai.xmb.utils.ValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * Created by caojian on 2017/3/30.
 */
@Controller
@RequestMapping("/sale/category")
@PreAuthorize("hasRole('ROLE_SALE')")
public class SaleCategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private GoodsService goodsService;

    /**
     * 分类列表
     *
     * @param map
     * @param model
     * @return
     */
    @GetMapping("")
    public Object index(@RequestParam Map map, Model model) {
        long saleId = SecurityUserUtil.getUser().getId();
        PageUtil.startPage(map);
        Page page = (Page) categoryService.getListBySaleId(saleId);
        model.addAttribute("categoryList", page.toPageInfo());
        return "sale-category-list";
    }

    /**
     * 增加分类
     *
     * @param category
     * @return
     */
    @PostMapping("")
    @ResponseBody
    public Object add(Category category) {
        long saleId = SecurityUserUtil.getUser().getId();
        category.setSaleId(saleId);
        categoryService.add(category);
        return AjaxMessage.newSuccessMsg(category);
    }

    /**
     * 更新分类
     *
     * @param categoryId
     * @param category
     * @return
     */
    @PostMapping("/{categoryId}")
    @ResponseBody
    public Object update(@PathVariable("categoryId") long categoryId, Category category) {
        ValidateUtil.isNull(category.getSaleId());
        category.setId(categoryId);
        categoryService.update(category);
        return AjaxMessage.newSuccessMsg(category);
    }

    /**
     * 删除分类
     *
     * @param categoryId
     * @return
     */
    @PostMapping("/{categoryId}/delete")
    @ResponseBody
    public Object delete(@PathVariable("categoryId") long categoryId) {
        if (goodsService.hasCategoryGoods(categoryId)) {
            return AjaxMessage.newErrorHintMsg("该分类下还有商品，不能删除！");
        }
        long saleId = SecurityUserUtil.getUser().getId();
        categoryService.delete(categoryId, saleId);
        return AjaxMessage.newSuccessMsg();
    }
}
